package com.example.hal.server;

import static com.googlecode.objectify.ObjectifyService.ofy;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import org.restlet.resource.ServerResource;

import com.example.hal.model.Utilisateur;
import com.googlecode.objectify.cmd.Query;
import com.googlecode.objectify.ObjectifyService;
import com.google.appengine.api.blobstore.*;
import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.files.AppEngineFile;
import com.google.appengine.api.files.FileService;
import com.google.appengine.api.files.FileServiceFactory;
import com.google.appengine.api.files.FileWriteChannel;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.ServingUrlOptions;

public class UtilisateurEditController	extends ServerResource implements
	 UtilisateurEditControllerInterface {
	static{

		 ObjectifyService.register(Utilisateur.class);
	}

	public UtilisateurEditController() {
		// TODO Auto-generated constructor stub
	}
	
	
	
	@Override
	public Utilisateur edit(Utilisateur user) {
		// TODO Auto-generated method stub

	     Logger log = Logger.getLogger(UtilisateurEditController.class.getName());

	        log.info("edit Utilisateur.");
		// Objectify ofy = ObjectifyService.begin();
		 

			  FileService fileService = FileServiceFactory.getFileService();
		// Utilisateur tp=  ofy.query(Utilisateur.class).filter("email", user.getEmail()).get();
	        Utilisateur tp=null;
	        Query<Utilisateur> query;
	     switch( user.getMode()){
	     case 0:   
	    	 query = ofy().load().type(Utilisateur.class).filter("email",  user.getEmail());
	         query.filter("mode", 0);
	         tp= query.first().now();
	    	// tp= ofy().load().type(Utilisateur.class).filter("email",  user.getEmail()).filter("mode", 0).first().now();
				break;
	     case 1:
	    	 query = ofy().load().type(Utilisateur.class).filter("idFacebook",  user.getIdFacebook());
	         query.filter("mode", user.getMode());
	 		tp= query.first().now();
	 		//tp = ofy().load().type(Utilisateur.class).filter("idFacebook",  user.getIdFacebook()).filter("mode", user.getMode()).first().now();
				break;
	     }
		 if(tp==null)
		 {

			 tp = new Utilisateur();
			 tp.setRetourHttp(1);
			 return tp;
		 }
		 else{
			 
			//	 Utilisateur u=q.get();
			 
			 if(user.getOldmdp()!=null && !user.getOldmdp().equals(""))
			 {
				 if(tp.getMdp().equals(user.getOldmdp()))
				 {
					 tp.setMdp(user.getMdp());
				 }
				 else
				 {
	
					 tp.setRetourHttp(2);
					 return tp;
				 }
			 }

			 
			 if(user.getImage()!=null && !user.getImage().equals(""))
			 {
				 byte[] data = user.getImage();
				  /**
				   *  MIME Type for
				   *  JPG use "image/jpeg" for PNG use "image/png"
				   *  PDF use "application/pdf"
				   *  see more: https://en.wikipedia.org/wiki/Internet_media_type
				   */
				  String mimeType = "image/png";
	
				  // save data to Google App Engine Blobstore 
				  AppEngineFile file;
				try {
					file = fileService.createNewBlobFile(mimeType,"u_"+tp.getId());
					  FileWriteChannel writeChannel = fileService.openWriteChannel(file, true);
					  writeChannel.write(java.nio.ByteBuffer.wrap(data));
					  writeChannel.closeFinally();
		
					  // your blobKey to your data in Google App Engine BlobStore
					  BlobKey blobKey = fileService.getBlobKey(file);
		
					  // THANKS TO BLOBKEY YOU CAN GET FOR EXAMPLE SERVING URL FOR IMAGES
		
					//  UploadOptions uploadOptions = UploadOptions.Builder
					//		  	.withGoogleStorageBucketName("photobucket11");
					  
					  // Get the image serving URL (in https:// format)
					  String imageUrl = ImagesServiceFactory.getImagesService().getServingUrl(ServingUrlOptions.Builder.withBlobKey(blobKey).secureUrl(true));

			     //       ImagesService imagesService = ImagesServiceFactory
			     //               .getImagesService();
			      //      ServingUrlOptions servingOptions = ServingUrlOptions.Builder
			     //               .withBlobKey(blobKey);

			     //       String imageUrl = imagesService.getServingUrl(servingOptions);
					  
					  if(tp.getIdBlobkey()!=null)
						 {
							 BlobKey blobKeytmp= new BlobKey(tp.getIdBlobkey());
							 final AppEngineFile f = fileService.getBlobFile(blobKeytmp);

						        if(f.isReadable())
						        {

						            if(f.hasFinalizedName())
						            {
						                fileService.delete(f); // Problematic line
						            }
						        }
							 
						 }
					  
					  	tp.setImage(user.getImage());
						 tp.setAvatar(imageUrl);
						 tp.setIdBlobkey(blobKey.getKeyString());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();

					 tp.setRetourHttp(3);
					 return tp;
				} 
				    
				    
				 
			 }
			 
			 
		//	 tp.setAvatar(user.getAvatar());
			// tp.setAvatar("test");
			 tp.setDateDerConnection(new Date());
			 tp.setDroit(user.getDroit());
			 tp.setEmail(user.getEmail());
			 tp.setLatitude(user.getLatitude());
			 tp.setLongitude(user.getLongitude());
			 tp.setMode(user.getMode());
			 tp.setNom(user.getNom());
			 tp.setPrenom(user.getPrenom());
			 tp.setStatut(user.getStatut());
			 tp.setIdFacebook(user.getIdFacebook());

			 ofy().save().entity(tp).now();
			 
			 tp.setRetourHttp(0);
			 
			 return tp;
		 }
		 

		// ofy.put(tp);
	}

}
